<?php 

namespace app\admin\controller;

use app\admin\model\Coupon as CouponMdl;
use \think\Request;
use app\admin\model\Store;
use app\admin\model\Couponuse;

class Coupon extends Base{
    public $week = ['1'=>'周一','2'=>'周二','3'=>'周三','4'=>'周四','5'=>'周五','6'=>'周六','7'=>'周天','8'=>'节假日不能使用'];

    public function __construct() {
        parent::__construct();
        $this->model = new CouponMdl();
    }

    public function index() {
        if(!$this->checkStore()) {
            return $this->fetch('public/alert');
        }
        
        $request = Request::instance();
        $param = $request->param();

        $store = Store::where(['tenantId'=>session('TENANT_ID')])->select();
        $storeId = empty($param) ? $store[0]['id'] : $param['storeId'];
        $this->assign('store',$store);
        $this->assign('storeId',$storeId);
        return $this->fetch();
    }

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数11
        $storeId = $param['storeId'];
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件
        $where = ['tenantId'=>session('TENANT_ID'),'storeId'=>$storeId];  //搜索条件
        if($param['search']['value']) {  //拼接搜索条件
            $curTime = time();
            $ss = json_decode($param['search']['value'],true);
            if($ss['status'] == '使用中') {
                $where['startTime'] = ['lt',$curTime];
                $where['endTime'] = ['gt',$curTime];
            } else if($ss['status'] == '已过期') {
                $where['endTime'] = ['lt',$curTime];
            } else if ($ss['status'] == '未开始') {
                $where['startTime'] = ['gt',$curTime];
            }
        }

        $list = $this->model->where($where)->limit($start,$length)->order($order)->select();
        $count = $this->model->where($where)->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];
        return json($res);
    }

    //添加代金券
    public function add() {
        $request = Request::instance();
        $storeId = $request->param('storeId');
        $store = Store::where('id',$storeId)->find();

        $this->assign('week',$this->week);
        $this->assign('storeId',$storeId);
        $this->assign('storeName',$store['name']);

        return $this->fetch();
    }

    public function edit() {
        $request = Request::instance();
        $id = $request->param('id');

        $row = $this->model->where(['id'=>$id])->find();
        $store = Store::where('id',$row['storeId'])->find();

        $this->assign('row',$row);
        $this->assign('storeName',$store['name']);
        $this->assign('week',$this->week);
        return $this->fetch();
        //dump($param);
    }

    //保存操作
    public function savePost() {
        $request = Request::instance();
        $param = $request->param();
        if($param['value1']){
            if($param['value1']<=$param['value2']){
                return json(['code'=>'2','message'=>'消费满减金额必须大于面值金额']);
            }
        }
        // return $param;        
        $param['useWeek'] = isset($param['useWeek']) && $param['useWeek'] ? implode(',', (array)$param['useWeek']) : '';

        if(isset($param['isLimit'])) {  //代金券总量不限
            if(is_array($param['isLimit'])) {
                if($param['getCond'] == 1 && $param['isLimit'][0]) {
                    $param['isLimit'] = 1;
                }
                if($param['getCond'] == 2 && $param['isLimit'][1]) {
                    $param['isLimit'] = 1;
                }
            }
        }
        
        $param['startTime'] = strtotime($param['startTime']);
        $param['endTime'] = strtotime($param['endTime'].'23:59:59');
        // return $param;
        
        if($param['id']) {  //编辑操作
            $auto = [
                'updateDate' => time(),
                'updateOper' => session('member')['id']
            ];
            $data = array_merge($param,$auto);
            $save = $this->model->update($data);
        } else {
            $param['id'] = get_uniqid_id();
            $auto = [
                'leftCount' => $param['totalCount'],
                'tenantId' => session('TENANT_ID'),
                'createDate' => time(),
                'updateDate' => time(),
                'createOper' => session('member')['id'],
                'updateOper' => session('member')['id']
            ];
            $data = array_merge($auto,$param);
            $save = $this->model->insert($data);
        }
        if($save) {
            return json(['status'=>'1','message'=>'保存成功']);
        } else {
            return json(['status'=>'2','message'=>'网络出错，请重试']);
        }
    }

    //无条件删除
    //用户每领取一个代金券，就将代金券的信息单独存储，使编辑与删除操作都不会影响之前已领取用户的使用
    public function delete() {
        $request = Request::instance();
        $id = $request->param('id');   //代金券ID

        $del = $this->model->where('id',$id)->delete();
        if($del) {
            return json(['status'=>'1','message'=>'删除成功']);
        } else {
            return json(['status'=>'2','message'=>'网络出错，请重试']);
        }
    }

    //查看代金券领取及使用记录
    public function useList() {
        $request = Request::instance();
        $id = $request->param('id');   //代金券ID

        $row = $this->model->field('a.*,b.name storeName')->alias('a')->join('store b','a.storeId=b.id')->where('a.id',$id)->find();
        $this->assign('row',$row);
        // dump($row);
        return $this->fetch();
    }

    public function useListApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数
        $couponId = $param['couponId'];
        $columns = $param['order'][0]['column'];
        $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];  //排序条件
        $where = ['couponId'=>$couponId];  //搜索条件

        if($param['search']['value']) {  //拼接搜索条件
            $curTime = time();
            $ss = json_decode($param['search']['value'],true);
            if($ss['status'] == '已使用') {
                $where['a.status'] = 1;
            } else if($ss['status'] == '未使用') {
                $where['a.status'] = 0;
            } else if($ss['status'] == '已过期') {
                $where['a.status'] = 0;  //只查询未使用的已过期优惠券
                $where['a.status'] = 0;
            }
        }

        $list = Couponuse::field('a.*,b.mobile,b.nickName')->alias('a')->join('user b','a.userId=b.id')->where($where)->limit($start,$length)->order($order)->select();
        $count = Couponuse::alias('a')->where($where)->count();
        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($res);
    }





}
